<template>
    <div :style="conheight">
        <Tabs value="name1" @on-click="clickTab">
            <TabPane label="分类统计" name="name1">
                <div>
                    <Form :label-width="100" ref="form1" :model="form1">
                        <Row  class="query-form2">
                            <Col span="8">
                                <FormItem label="开始范围：" prop="reportDate">
                                    <DatePicker type="daterange" style="width: 100%"  v-model="dateRange"  format="yyyy-MM-dd"  placeholder="请选择" ></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="8">
                                <FormItem label="组织机构：" prop="orgId" >
                                    <cascaderDom style="width: 100%" ref="childConOrg1"  @setOrgInfo="setOrgId"  @setOrgname="setOrgName" :currentOrgId = "form1.orgId"
                                                :currentOrgName = "form1.orgName"   :orgTree = "true"  ></cascaderDom>
                                </FormItem> 
                            </Col>
                            <Col span="8">
                                <div style="float: right;">
                                    <Button class="ivu-btn-query"  icon="md-search"  @click="queryByType">查询</Button>
                                    <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                                </div>
                            </Col>
                        </Row>
                    </Form>
                    <Table ref='table'  height="750" :loading="loading" border :columns="columns1"  :data="dataTable1">
                    </Table>
                </div>
            </TabPane>
            <TabPane label="单位/状态统计" name="name4">
                <Form :label-width="100" ref="form1" :model="form1">
                    <Row  class="query-form2">
                        <Col span="8">
                            <FormItem label="开始范围：" prop="reportDate">
                                <DatePicker type="daterange" style="width: 100%"  v-model="dateRange"  format="yyyy-MM-dd"  placeholder="请选择" ></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="8">
                                <FormItem label="组织机构：" prop="orgId" >
                                    <cascaderDom style="width: 100%" ref="childConOrg4"  @setOrgInfo="setOrgId"  @setOrgname="setOrgName" :currentOrgId = "form1.orgId"
                                                :currentOrgName = "form1.orgName"   :orgTree = "true"  ></cascaderDom>
                                </FormItem> 
                        </Col>
                        <Col span="8">
                            <div style="float: right;">
                                <Button class="ivu-btn-query"  icon="md-search"  @click="queryByDeptAndStatus(companyId)">查询</Button>
                                <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                            </div>
                        </Col>
                    </Row>
                </Form>
                <div style="width:100%;display:flex;justify-content:center;margin:20px">
                    <div style="margin-left:30px;display:flex">
                        <div style="margin-right:10px;width:40px;height:20px;background-color:white;border:1px solid black"></div>
                        <span>正常</span>
                    </div>
                    <div style="margin-left:30px;display:flex">
                        <div style="margin-right:10px;width:40px;height:20px;background-color:yellow;border:1px solid black"></div>
                        <span>延期</span>
                    </div>
                    <div style="margin-left:30px;display:flex">
                        <div style="margin-right:10px;width:40px;height:20px;background-color:red;border:1px solid black"></div>
                        <span>未关闭</span>
                    </div>
                </div>
                <div style="width:100%;display:flex;flex-direction:column">
                  <Spin style="margin-left:45%;margin-top:200px" size="large"  v-if="loading"></Spin>
                    <table v-else>
                        <caption>
                            单位
                        </caption>
                        <tr v-if="dataTable4.deptDetail.length<7">
                            <td v-for="index1 of dataTable4.deptDetail.length" style="cursor:pointer" >
                                <div style="display:flex;flex-direction:column;justify-content:space-between;width:100%;height:100%">
                                    <p style="flex:auto;width:100%;height:100%;border-bottom:1px solid black" @click="queryByDeptAndStatus(dataTable4.deptDetail[index1-1].orgId)">
                                      {{dataTable4.deptDetail[index1-1].orgName}}</p>
                                    <p style="flex:auto;height:30px;width:100%;border-bottom:1px solid black">{{dataTable4.deptDetail[index1-1].totalNum}}</p>
                                    <div style="flex:auto;height:30px;width:100%;display:flex;">
                                        <p style="flex:auto;border-right:1px solid black">{{dataTable4.deptDetail[index1-1].ptwNum1}}</p>
                                        <p @click="queryPtwListByOrgId(dataTable4.deptDetail[index1-1].orgId)"
                                           :class="dataTable4.deptDetail[index1-1].ptwNum2>0?yanchiCss:''" style="flex:auto;border-right:1px solid black">{{dataTable4.deptDetail[index1-1].ptwNum2}}</p>
                                        <p @click="queryPtwListByOrgId(dataTable4.deptDetail[index1-1].orgId)"
                                           :class="dataTable4.deptDetail[index1-1].ptwNum3>0?weiguanbiCss:''" style="flex:auto">{{dataTable4.deptDetail[index1-1].ptwNum3}}</p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr v-else="dataTable4.deptDetail.length>6" v-for="index of dataTable4.deptDetail.length/6">
                            <td v-for="index1 of 6"  style="cursor:pointer" >
                                <div style="display:flex;flex-direction:column;justify-content:space-between;width:100%;height:100%">
                                    <p style="flex:auto;width:100%;height:100%;border-bottom:1px solid black" @click="queryByDeptAndStatus(dataTable4.deptDetail[index1-1].orgId)">{{dataTable4.deptDetail[(index-1)*6+index1-1].orgName}}</p>
                                    <p style="flex:auto;width:100%;height:30px;border-bottom:1px solid black">{{dataTable4.deptDetail[(index-1)*6+index1-1].totalNum}}</p>
                                    <div style="flex:auto;width:100%;display:flex;">
                                        <p @click="queryPtwListByOrgId(dataTable4.deptDetail[(index-1)*6+index1-1].orgName,'1')" style="flex:auto;height:30px;border-right:1px solid black">{{dataTable4.deptDetail[(index-1)*6+index1-1].ptwNum1}}</p>
                                        <p @click="queryPtwListByOrgId(dataTable4.deptDetail[(index-1)*6+index1-1].orgName,'2')"
                                           :class="dataTable4.deptDetail[(index-1)*6+index1-1].ptwNum2>0?yanchiCss:''" style="flex:auto;border-right:1px solid black">{{dataTable4.deptDetail[(index-1)*6+index1-1].ptwNum2}}</p>
                                        <p @click="queryPtwListByOrgId(dataTable4.deptDetail[(index-1)*6+index1-1].orgName,'3')"
                                           :class="dataTable4.deptDetail[(index-1)*6+index1-1].ptwNum3>0?weiguanbiCss:''" style="flex:auto">{{dataTable4.deptDetail[(index-1)*6+index1-1].ptwNum3}}</p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>合计</td>
                            <td colspan="5">{{dataTable4.total}}</td>
                        </tr>
                    </table>
                </div>
            </TabPane>
        </Tabs>
      <Modal title="作业许可列表" v-model="ptwModal" width="1200" :mask-closable="false" footer-hide>
        <Table ref='table2' :loading="ptwLoading" no-data-text="请选择查询条件!" border :height="tableHeight"
               :columns="column"  width="100%" :data="ptwLists" size="small"></Table>
        <Row type="flex" justify="end" >
          <i-col>
            <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                  @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
          </i-col>
        </Row>
      </Modal>
    </div>
</template>

<script>

    import echarts from 'echarts'
    import {Api} from '../../../../api/index.js'
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import { sessionStorage, cookie } from '../../../../common/cacheUtils.js';
	export default {
        components: {
            cascaderDom
        },
		data() {
			return {
        companyId:sessionStorage('userId').getObject('userId').companyId,
        currentTab:"name1",
        conheight:{
            height:''
        },
        yanchiCss:'yanchiCss',
        weiguanbiCss: 'weiguanbiCss',
        loading: false,
        ptwLoading:false,
        dataTable1:[],
        dataTable2:[],
        ptwLists:[],
        dataTable3:{deptDetail:[]},
        dataTable4:{deptDetail:[]},
        dateRange:[],
        tableHeight:0,
        pageSizeArray: [10, 20, 50],
        pagedata: {
          total: 0, //总条数
          currentPage: 1,//从n条开始
          pageSize: 10//每页多少条
        },
        form1:{
            startDate:"",
            endDate:"",
            orgId:"",
            orgName:"",
            userId:""
        },
        columns1: [
            {
                title:"作业统计",
                align: 'center',
                children:[],
            }
        ],
        currentOrgId:'',
        currentStatus:'',
        ptwModal: false,
        column:[
          {
            title: '序号',
            width: 100,
            align: 'center',
            render: (h, params) => {
              return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
            }
          },
          {
            minWidth: 150,
            title: '任务名称',
            key: 'planName',
            align: 'center'
          },
          {
            minWidth: 150,
            title: '任务许可证类型',
            key: 'modelTypeName',
            align: 'center'
          },
          {
            minWidth: 150,
            title: '所属单位',
            key: 'belongOrgName',
            align: 'center'
          },
          {
            minWidth: 150,
            title: '作业单位',
            key: 'operateOrgName',
            align: 'center'
          },
          {
            minWidth: 150,
            title: '作业部门',
            key: 'workDept',
            align: 'center'
          },
          {
            minWidth: 150,
            title: '作业开始时间',
            key: 'applyStartDate',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                (this.formatDate(new Date(params.row.applyStartDate), 'yyyy-MM-dd'))
              ]);
            }
          },
          {
            minWidth: 150,
            title: '作业结束时间',
            key: 'applyEndDate',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                (this.formatDate(new Date(params.row.applyEndDate), 'yyyy-MM-dd'))
              ]);
            }
          },
          {
            minWidth: 150,
            title: '状态',
            key: 'status',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                (params.row.ptwStatus == '0' ? '未上报' :
                    params.row.ptwStatus == '1' ? '审批中' :
                        params.row.ptwStatus == '2' ? '作业中' :
                            params.row.ptwStatus == '3' ? '已关闭' :
                                params.row.ptwStatus == '4' ? '已过期' :
                                    params.row.ptwStatus == '5' ? '延期关闭' : '')
              ]);
            }
          },
        ],
        columns2: [
            {
                title:"作业许可月度统计",
                align: 'center',
                children:[],
            }
        ],
        columns4: [
            {
                title:"作业许可月度统计",
                align: 'center',
                children:[],
            }
        ],
        ptwTypeList:[],
        workGradeList:[]
      }
    },
    async mounted(){
        this.conheight.height=window.innerHeight-120+'px';
        this.form1.orgId = sessionStorage('userId').getObject('userId').companyId;
        this.form1.orgName = sessionStorage('userId').getObject('userId').companyName;
        this.form1.userId = sessionStorage('userId').getObject('userId').userId;
        this.tableHeight = window.innerHeight - 300;
        await this.selectCodingSort();
        this.queryByType();
        this.queryByDeptAndStatus(sessionStorage('userId').getObject('userId').companyId);
    },
    methods:{
        async selectCodingSort() {
          this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100004', {params: {}}).then((res) => {
            this.workGradeList = res.data.data;
          })
          await this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100001', {params: {}}).then((res) => {
            this.ptwTypeList = res.data.data;
            let index = 0;
            this.columns1[0].children.push({
              title: '月份',
              align: 'center',
              key: "monthNum",
            })
            res.data.data.forEach(item=>{
              this.columns1[0].children.push({
                title: item.codingName,
                align: 'center',
                key: "num" + index,
              })
              index++;
            });
            this.columns1[0].children.push({
              title: '合计',
              align: 'center',
              key: "sum",
            })
          })
        },
        queryByType(){
            this.loading = true;
            this.form1.startDate = "";
            this.form1.endDate = "";
            if (this.dateRange[0]!=""&&this.dateRange[1]!=""){
                this.form1.startDate =  this.formatDate(new Date(this.dateRange[0]), 'yyyy-MM-dd') + ' 00:00';
                this.form1.endDate = this.formatDate(new Date(this.dateRange[1]), 'yyyy-MM-dd') + ' 24:00';
            }
            this.dataTable1.splice(0,this.dataTable1.length);
            let url = Api.statisticsPtwByPtwType;
            this.$http.get(url, {params: this.form1}).then((res) => {
                this.loading = false;
                let sumNum0 = 0;
                let sumNum1 = 0;
                let sumNum2 = 0;
                let sumNum3 = 0;
                let sumNum4 = 0;
                let sumNum5 = 0;
                let sumNum6 = 0;
                let sumNum7 = 0;
                let sumNum8 = 0;
                let sumNum9 = 0;
                let sumNum10 = 0;
                let sumNum11 = 0;
                let sumNum12 = 0;
                let sumNum13 = 0;
                let sumNum14 = 0;
                let sumNum15 = 0;
                let sumNum16 = 0;
                res.data.forEach(item=>{
                  item.sum = item.num0 + item.num1 + item.num2 + item.num3 + item.num4 + item.num5 + item.num6 + item.num7
                   + item.num8 + item.num9 + item.num10 + item.num11 + item.num12 + item.num13 + item.num14 + item.num15 + item.num16;
                  sumNum0 += item.num0;
                  sumNum1 += item.num1;
                  sumNum2 += item.num2;
                  sumNum3 += item.num3;
                  sumNum4 += item.num4;
                  sumNum5 += item.num5;
                  sumNum6 += item.num6;
                  sumNum7 += item.num7;
                  sumNum8 += item.num8;
                  sumNum9 += item.num9;
                  sumNum10 += item.num10;
                  sumNum11 += item.num11;
                  sumNum12 += item.num12;
                  sumNum13 += item.num13;
                  sumNum14 += item.num14;
                  sumNum15 += item.num15;
                  sumNum16 += item.num16;
                })
                res.data.push({
                  monthNum:'合计',
                  num0:sumNum0,
                  num1:sumNum1,
                  num2:sumNum2,
                  num3:sumNum3,
                  num4:sumNum4,
                  num5:sumNum5,
                  num6:sumNum6,
                  num7:sumNum7,
                  num8:sumNum8,
                  num9:sumNum9,
                  num10:sumNum10,
                  num11:sumNum11,
                  num12:sumNum12,
                  num13:sumNum13,
                  num14:sumNum14,
                  num15:sumNum15,
                  num16:sumNum16,
                  sum: sumNum0 + sumNum1 + sumNum2 + sumNum3 + sumNum4 + sumNum5 + sumNum6 + sumNum7 + sumNum8 + sumNum9
                   + sumNum10 + sumNum11 + sumNum12 + sumNum13 + sumNum14 + sumNum15 + sumNum16
                })
                this.dataTable1 = res.data;
            }).catch(e => {
                this.$Message.error("数据获取失败")
            })
        },
        pageChange(pageNum) {
          this.pagedata.currentPage = pageNum;
          this.queryPtwListByOrgId(this.currentOrgId,this.currentStatus);
        },
        pageSizeChange(pageSize) {
          this.pagedata.pageSize = pageSize;
          this.queryPtwListByOrgId(this.currentOrgId,this.currentStatus);
        },
        queryPtwListByOrgId(orgName,status){
          this.ptwModal = true;
          this.ptwLoading = true;
          this.currentStatus = status;
          this.currentOrgId = orgName;
          let data = {
            currentPage: this.pagedata.currentPage,
            size: this.pagedata.pageSize,
            userId: sessionStorage('userId').getObject('userId').userId,
            belongOrgName: orgName
          }
          if(status == '1'){
            data.ptwStatus = "'3'";
          }else if(status == '2'){
            data.ptwStatus = "'4','5'";
          }else{
            data.ptwStatus = "'1','2','0'";
          }
          let url = Api.getPtwList;
          this.$http.get(url, {params: data}).then((res) => {
            this.ptwLists = res.data.data;
            this.pagedata.total = res.data.totalSize;
            this.loading = false;
            this.ptwLists.forEach(item => {
              this.ptwTypeList.forEach(item1 => {
                if (item1.codingCodeId == item.ptwType)
                  item.ptwTypeName = JSON.parse(JSON.stringify(item1.codingName));
                ;
              })
              this.workGradeList.forEach(item2 => {
                if (item2.codingCodeId == item.workGrade)
                  item.workGradeName = item2.codingName;
              })
            })
            this.ptwLoading = false;
          }).catch(e => {
            this.$Message.error("数据获取失败")
          })
        },
        queryByDeptAndStatus(orgId){
            this.dataTable4 = {deptDetail:[]};
            this.loading = true;
            this.form1.orgId = orgId;
            this.form1.startDate = "";
            this.form1.endDate = "";
            if (this.dateRange[0]!=""&&this.dateRange[1]!=""){
                this.form1.startDate =  this.formatDate(new Date(this.dateRange[0]), 'yyyy-MM-dd');
                this.form1.endDate = this.formatDate(new Date(this.dateRange[1]), 'yyyy-MM-dd');
            }
            let url = Api.statisticsPtwByDeptAndStatus;
            this.$http.get(url, {params: this.form1}).then((res) => {
                this.loading = false;
                this.dataTable4 = res.data;
                if((this.dataTable4.deptDetail.length/6)>1 &&this.dataTable4.deptDetail.length%6 != 0){
                    for(var i=this.dataTable4.deptDetail.length%6;i<6;i++){
                        this.dataTable4.deptDetail.push({orgName:"",totalNum:"",ptwNum1:"",ptwNum2:"",ptwNum3:""});
                    }
                }
            }).catch(e => {
                this.$Message.error("数据获取失败")
            })
        },
        setOrgId(data) {
            this.form1.orgId = data[data.length - 1];
        },
        setOrgName(data){
            this.form1.orgName = data;
        },
        clickTab(name){
            this.form1.orgId = sessionStorage('userId').getObject('userId').companyId;
            this.form1.orgName = sessionStorage('userId').getObject('userId').companyName;
            this.form1.userId = sessionStorage('userId').getObject('userId').userId;
            this.dateRange = ["",""];
            this.currentTab = name;
            if(this.currentTab == "name1")
                this.queryByType();
            if(this.currentTab == "name4")
                this.queryByDeptAndStatus(sessionStorage('userId').getObject('userId').companyId);
        },
        reset(){
            this.form1.orgId = sessionStorage('userId').getObject('userId').companyId;
            this.form1.orgName = sessionStorage('userId').getObject('userId').companyName;
            this.form1.userId = sessionStorage('userId').getObject('userId').userId;
            this.dateRange = ["",""];
            setTimeout(() => {
                this.$refs.childConOrg1.resetCurrentOrg()
                this.$refs.childConOrg4.resetCurrentOrg()
            }, 200)
            if(this.currentTab == "name1") {
                this.queryByType();
            }
            if(this.currentTab == "name4") {
                this.queryByDeptAndStatus(sessionStorage('userId').getObject('userId').companyId);
            }
        },
        getTypeOption(){
            let option = {
                title: {
                    text: '',
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    right: 10,
                    data: []
                },
                color:['#42A5F5', '#FF3E80', '#FFC310', '#1DE9B6'],
                series: [
                    {
                        name: '作业统计',
                        type: 'pie',
                        radius: '60%',
                        center: ['40%', '50%'],
                        label: {
                            formatter: '{@2012} ({d}%)'
                        },
                        data: [

                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            return option;
        },
        getMonthBarOption(){
            let option = {
                title: {
                    text: '',
                    textStyle: {
                        fontSize: 14
                    }
                },
                color: ['#1DE9B6', '#42A5F5'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    top: '20%',
                    left: '3%',
                    right: '4%',
                    bottom: '1%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: [],
                        axisTick: {show: false},
                        splitLine:{show: false},
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: '#757575'
                            }
                        },
                        axisLabel: {
                            fontSize:12
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisTick: {show: false},
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: '#757575'
                            }
                        },
                        axisLabel: {
                            fontSize:12
                        }
                    }
                ],
                series: [
                    {
                        type: 'bar',
                        barGap: 0,
                        barWidth: 18,
                        barCategoryGap:'50%',
                        data: [],
                        itemStyle:{
                            emphasis: {
                                barBorderRadius: 30
                            },
                            normal: {
                                //柱形图圆角，初始化效果
                                barBorderRadius:[10, 10, 0, 0],
                            }
                        }
                    },
                ]
            };
            return option;
        },
        formatDate(date, fmt) {
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            let o = {
                'M+': date.getMonth() + 1,
                'd+': date.getDate(),
                'h+': date.getHours(),
                'm+': date.getMinutes(),
                's+': date.getSeconds()
            };
            for (let k in o) {
                if (new RegExp(`(${k})`).test(fmt)) {
                    let str = o[k] + '';
                    fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                }
            }
            return fmt;
        },
        padLeftZero(str) {
            return ('00' + str).substr(str.length);
        }
    }
    }
</script>
<style scoped>

table{
    border-collapse: collapse;
    border-spacing: 0px;
}

table,tr,td,caption{
    text-align:center;
    border:1px solid black;
    border-collapse: collapse;
    border-spacing: 0px;
}

td{
    height:80px;
}

.yanchiCss{
    background-color:yellow;
}

.weiguanbiCss{
    background-color:red;
}

</style>